/**
 * Created by bestick on 2015/12/27.
 * 全局函数库
 */

/**
 * Json渲染
 * @param tempId 模版id
 * @param domId 目标dom的id
 * @param data json数据
 * @param callback 回调，非必须
 */
function $render(tempId, domId, data, callback) {
    $.views.helpers(commonHelpers);
    var template = $.templates(tempId);
    var htmlOutput = template.render(data);
    $(domId).html(htmlOutput);
    if ($.isFunction(callback)) {
        callback();
    }
}

/**
 * Ajax请求返回Json成功则调用$render
 * @param url 请求的url
 * @param args 对应的参数
 * @param map 模版id和目标dom的id的一个json串
 * @param callback 回调，非必须
 */
function doRender(url, args, map, callback) {
    var $ajax = $.ajax({
        type: "GET",
        url: url,
        data: args,
        dataType: "json",
        timeout: 15000,
        success: function (data) {
            for (var prop in map) {
                if (map.hasOwnProperty(prop)) {
                    console.log(prop + ":" + map[prop]);
                    $render(prop, map[prop], data);
                }
            }
        },
        complete: function (XMLHttpRequest, status) {
            if (status == "error") {
                alert("error code: " + XMLHttpRequest.status);
            } else if (status == "timeout") {
                $ajax.abort();
                alert('请求超时');
            }
            if ($.isFunction(callback)) {
                callback(XMLHttpRequest);
            }
        }
    });
}

/**
 * 向服务器提交数据
 * @param url 请求的url
 * @param args 对应参数
 * @param callback 回调，非必须
 */
function doPost(url, args, callback) {
    var $ajax = $.ajax({
        type: "GET",
        url: url,
        data: args,
        timeout: 15000,
        success: function (data) {
            alert(data.msg);
        },
        complete: function (XMLHttpRequest, status) {
            if (status == "error") {
                alert("error code: " + XMLHttpRequest.status);
            } else if (status == "timeout") {
                $ajax.abort();
                alert('请求超时');
            }
            if ($.isFunction(callback)) {
                callback(XMLHttpRequest, status);
            }
        }
    });
}

/**
 * 同步请求，返回responseJSON
 * @param url 请求的url
 * @param args 对应参数
 * @param callback 回调，非必须
 * @returns responseJSON
 */
function syncRequest(url, args, callback) {
    var $ajax = $.ajax({
        type: "GET",
        async: false,
        url: url,
        data: args,
        dataType: "json",
        success: function () {
        },
        complete: function (XMLHttpRequest, status) {
            if (status == "error") {
                alert("error code: " + XMLHttpRequest.status);
            } else if (status == "timeout") {
                $ajax.abort();
                alert('请求超时');
            }
            if ($.isFunction(callback)) {
                callback(XMLHttpRequest);
            }
        }
    });
    return $ajax.responseJSON;
}

/**
 * 获取当前时间戳
 * @returns {number} unix时间戳
 */
function now() {
    return new Date().getTime();
}

/**
 * 创建一个StringBuffer方法
 * @constructor
 */
function StringBuffer() {
    this.__strings__ = [];
}
StringBuffer.prototype.append = function (str) {
    this.__strings__.push(str);
};
StringBuffer.prototype.toString = function () {
    return this.__strings__.join('');
};

//jsRender自定义标签
$.views.tags({
    sysConstants: function (context, option) {
        if (sysConstants) {
            return sysConstants['contants'][option][context];
        } else {
            return context;
        }
    },
    feeBuyRange: function (length, index, floor, top, standardBuyRate, rateType) {
        var floorFormat = (floor == 0 || floor == null) ? '' : (commonHelpers.moneyFormat(floor) + '≤');
        var topFormat = (top == 0 || top == null) ? "" : ('<' + commonHelpers.moneyFormat(top));
        var td1 = '<td rowspan=" ' + length + '" class="head">前端申购</td>';
        var td2 = '<td class="text-left">' + floorFormat + '申购金额' + topFormat + '<span class="pull-right">' + standardBuyRate.toFixed(2) + rateType + '</span></td>';
        return index == 0 ? '<tr>' + td1 + td2 + '</tr>' : '<tr>' + td2 + '</tr>';
    },
    feeTimeRange: function (length, index, floor, top, timeType, realBuyRate, rateType) {
        var floorFormat = (floor == 0 || floor == null) ? '' : (floor + timeType + '≤');
        var topFormat = (top == 0 || top == null) ? "" : ('<' + top + timeType);
        var td1 = '<td rowspan=" ' + length + '" class="head">赎回</td>';
        var td2 = '<td class="text-left">' + floorFormat + '持有期限' + topFormat + '<span class="pull-right">' + realBuyRate.toFixed(2) + rateType + '</span></td>';
        return index == 0 ? '<tr>' + td1 + td2 + '</tr>' : '<tr>' + td2 + '</tr>';
    }
});

//自定义辅助函数
var commonHelpers = {
    wan: function (context) {
        if (context == undefined || context == "") return 0;
        var money = context.toString() * 1;
        return Math.round(money / 10000 * 100) / 100;
    },
    moneyFormat: function (context) {
        if (context == undefined || context == "") return 0;
        var money = context.toString() * 1;
        if (money >= 10000000) {
            return Math.round(money / 100000000 * 100) / 100 + "亿";
        }
        if (money >= 10000) {
            return Math.round(money / 10000 * 100) / 100 + "万";
        }
        return money + "元";
    },
    portionFormat: function (context) {
        if (context == undefined || context == "") return 0;
        var portion = context.toString() * 1;
        if (portion >= 10000000) {
            return Math.round(portion / 100000000 * 100) / 100 + "亿份";
        }
        if (portion >= 10000) {
            return Math.round(portion / 10000 * 100) / 100 + "万份";
        }
        return portion + "分";
    },
    dateFormat: function (context, type) { //e.g. a(原样返回): yyyy-mm-dd hh:mm:ss, b(数字格式化yyyy-mm-dd): 20151114, c(去掉time,返回date): yyyy-mm-dd hh:mm:ss
        var date;
        var day;
        var month;
        var year;
        if (type == "a") {
            return context.toString();
        }
        if (type == "b") {
            date = context.toString();
            year = date.substring(0, 4);
            month = date.substring(4, date.length - 2);
            month = (month.length == 2) ? month : ('0' + month);
            day = date.substring(date.length - 2);
            return year + '-' + month + '-' + day;
        }
        if (type == "c") {
            year = context.substring(2, 4);
            month = context.substring(5, 7);
            date = context.substring(8, 10);
            return year + "-" + month + "-" + date;
        }
        return context;
    },
    doubleFormat: function (context) {
        if (context == undefined || context == "") return 0.00;
        return (context * 1).toFixed(2);
    },
    birthDateFormat: function (userBirthday) {
        if (userBirthday == "" || userBirthday == undefined) {
            return "未知";
        }
        var year = userBirthday.substring(0, 4);
        var month = userBirthday.substring(5, 7);
        var day = userBirthday.substring(8, 10);
        return year + "年" + month + "月" + day + "日";
    },
    getPcSuffixPic: function (picPosition) {
        if (picPosition == undefined || picPosition == "") return "";
        var prefix = picPosition.substring(0, picPosition.indexOf('.'));
        var suffix = picPosition.substring(picPosition.indexOf('.'));
        return prefix + '_pc' + suffix;
    },
    comboRisk: function (comboRank) {
        if (comboRank == undefined || comboRank == "") return "未知";
        var risk = ['低', '较低', '中', '较高', '高'];
        return risk[comboRank - 1];
    },
    comboBRFormat: function (rate) {
        if (rate == undefined || rate == "") return 0.00;
        return (rate * 100).toFixed(2);
    }
};

/**
 * 动态获取分页组件
 * @param total 记录总数
 * @param count 每页显示记录数
 * @param nowPage 当前页码
 */
function genPagination(total, count, nowPage) {
    var buffer = new StringBuffer();
    //TODO 总数为0的时候分页组件样式
    if (total == 0) {
        buffer.append('<div class="page-nav jcb-page-nav"><ul class="pagination jcb-pagination">');
        buffer.append("<li><a class='jcb-page-first' data-page='1'>首页</a></li>");
        buffer.append("<li class='disabled'><a class='jcb-page-pre' data-page='1'>上一页</a></li>");
        buffer.append("<li class='active'><a class='jcb-page-this' data-page='1'>1</a></li>");
        buffer.append("<li class='disabled'><a class='jcb-page-next' data-page='1'>下一页</a></li>");
        buffer.append("<li><a class='jcb-page-last' data-page='1'>末页</a></li>");
        buffer.append('</ul></div>');
        return buffer.toString();
    }
    //总页数
    var totalPage = total % count == 0 ? total / count : parseInt(total / count) + 1;
    buffer.append('<div class="page-nav jcb-page-nav"><ul class="pagination jcb-pagination">');
    //首页
    buffer.append("<li><a class='jcb-page-first' data-page='1'>首页</a></li>");
    //上一页逻辑
    if (nowPage == 1) {
        buffer.append("<li class='disabled'><a class='jcb-page-pre' data-page='" + nowPage + "'>上一页</a></li>");
    } else {
        buffer.append("<li><a class='jcb-page-pre' data-page='" + eval(nowPage - 1) + "'>上一页</a></li>");
    }
    //中间页逻辑
    for (var i = nowPage - 2; i <= nowPage + 2; i++) {
        if (i < 1 || i > totalPage) {
            continue;
        }
        if (i == nowPage) {
            buffer.append("<li class='active'><a class='jcb-page-this' data-page='" + i + "'>" + i + "</a></li>");
        } else {
            buffer.append("<li><a class='jcb-page-this' data-page='" + i + "'>" + i + "</a></li>");
        }
    }
    //下一页逻辑
    if (nowPage == totalPage) {
        buffer.append("<li class='disabled'><a class='jcb-page-next' data-page='" + totalPage + "'>下一页</a></li>");
    } else {
        buffer.append("<li><a class='jcb-page-next' data-page='" + eval(nowPage + 1) + "'>下一页</a></li>");
    }
    //末页
    buffer.append("<li><a class='jcb-page-last' data-page='" + totalPage + "'>末页</a></li>");

    buffer.append('</ul></div>');
    return buffer.toString();
}

/**
 * 分页实现
 * @param callback 回调，必须
 * @param nowPage 当前页码
 */
function initPagination(callback, nowPage) {

    var args = arguments;

    $('.jcb-page-first').click(function () {
        if (nowPage == 1) return;
        nowPage = 1;
        callback.apply(null, args);
    });

    $('.jcb-page-last').click(function () {
        if (nowPage == $(this).data('page')) return;
        nowPage = $(this).data('page');
        callback.apply(null, args);
    });

    $('.jcb-page-next').click(function () {
        if (nowPage >= $(this).data('page')) return;
        nowPage++;
        callback.apply(null, args);
    });

    $('.jcb-page-pre').click(function () {
        if (nowPage <= $(this).data('page')) return;
        nowPage--;
        callback.apply(null, args);
    });

    $('.jcb-page-this').click(function () {
        if (nowPage == $(this).data('page')) return;
        nowPage = $(this).data('page');
        callback.apply(null, args);
    });
}

/**
 * 初始化理财计算器
 */
function initJCBCalculator() {
    var $jcb_cal_slider = $('#jcb-calculator-slider');
    var $jcb_cal_amount = $('#jcb-cal-amount');
    var $jcb_cal_sum = $('#jcb-cal-sum');
    var $jcb_cal_yield = $('#jcb-cal-yield');
    var $jcb_cal_term = $('#jcb-cal-term');
    $jcb_cal_slider.slider({
        tooltip: 'always'
    });
    //ctrl
    $('.jcb-cal-slider .slider-track').on("click", function () {
        $jcb_cal_amount.val($('#jcb-calculator-slider').val());
        $jcb_cal_sum.text(($jcb_cal_amount.val() * $jcb_cal_yield.text() / 100 * $jcb_cal_term.val()).toFixed(2));
        initJcbCalChart();
    });
    $jcb_cal_slider.bind("slide", function (evt) {
        $jcb_cal_amount.val(evt.value);
        $jcb_cal_sum.text((evt.value * $jcb_cal_yield.text() / 100 * $jcb_cal_term.val()).toFixed(2));
        initJcbCalChart();
    });
    //TODO reverse-ctrl
    $jcb_cal_amount.bind("input propertychange", function () {
        //重新加载slider
        $('#jcb-calculator-slider').attr('data-slider-value', $(this).val()).slider();
    });
}

/**
 * 初始化理财计算器图表
 */
function initJcbCalChart() {
    $(function () {
        $('#jcb-cal-chart').highcharts({
            chart: {
                type: 'column',
                animation: false
            },
            title: {
                text: '收益本金图表'
            },
            xAxis: {
                categories: ['24month']
            },
            yAxis: {
                title: {
                    text: '万元'
                }
            },
            credits: {
                enabled: false
            },
            series: [{
                name: '本金',
                data: [Number($('#jcb-calculator-slider').val())],
                color: '#fed65a'
            }, {
                name: '收益',
                data: [Number(($('#jcb-cal-amount').val() * $('#jcb-cal-yield').text() / 100 * $('#jcb-cal-term').val()).toFixed(2))],
                color: '#d3d9df'
            }]
        });
    });
}